import { onBeforeUpdate, type Ref, ref } from 'vue';

/**
 * @description 循环生成 refs
 * @author wfd
 * @date 2022/11/14 20:18
 * @example const [refs, setRefs] = useRefs<TabContentExpose>();
 * @returns {readonly [Ref<T[]>, ((index: number) => (el: unknown) => void)]}
 */
export function useRefs<T = Element> () {
  const refs = ref([]) as Ref<T[]>;
  const cache: Array<(el: unknown) => void> = [];
  
  onBeforeUpdate(() => {
    refs.value = [];
  });
  
  const setRefs = (index: number) => {
    if (!cache[index]) {
      cache[index] = (el: unknown) => {
        refs.value[index] = el as T;
      };
    }
    return cache[index];
  };
  
  return [refs, setRefs] as const;
}
